import datetime
import time
from typing import List

from db.common.VideoManage.VideoQuality.conf import TaskCycleDB
from db.common.VideoManage.VideoQuality.inspection_plan import InspectionPlanDB
from db.common.VideoManage.VideoQuality.inspection_task import InspectionTaskDB
from server.common.VideoManage.VideoQuality.inspection_task import InspectionTaskServer


class PlanServer:

    def __init__(self):
        self.begin_time = int(time.time())
        self.end_time = int(
            time.mktime(time.strptime(str(datetime.date.today() + datetime.timedelta(days=1)), '%Y-%m-%d'))) - 1
        # 任务周期字典
        self.cycle_dict = TaskCycleDB('TaskCycle').use_keys([])

    def __generate_task(self, plan_code: str, plan_items: dict) -> List[dict]:
        """
        生成定时任务
        :param plan_code: 任务code
        :param plan_items: 任务详情
        """

        res_list = []
        # 根据任务周期判断是每天生成多次还是多天生成一次
        interval = self.cycle_dict.get(plan_items['task_cycle_code'])['minute'] * 60  # 任务时间间隔、单位 秒
        if 0 < interval <= 1440 * 60:

            i = 1  # 每天同一计划生成的任务序号
            while self.begin_time + interval < self.end_time:
                res_list.append({**plan_items, **{'name': plan_items['name'] + time.strftime('%y%m%d') + str(i),
                                                  'begin_time': self.begin_time + interval
                                                  }})
                interval += self.cycle_dict.get(plan_items['task_cycle_code'])['minute'] * 60
                i += 1

        else:
            task_dict = InspectionTaskDB().simple_list(inspection_plan_code=plan_code, order_by='begin_time', is_desc=1)
            if task_dict and self.end_time > task_dict[next(iter(task_dict))]['begin_time'] + interval:
                res_list.append({**plan_items, **{
                    'name': plan_items['name'] + time.strftime('%y%m%d') + str(1),
                    'begin_time': task_dict[next(iter(task_dict))]['begin_time'] + interval
                }})

        return res_list

    def start(self):
        """
        开始执行计划
        """

        # 获取所有需要生成task的巡检任务
        plan_dict = InspectionPlanDB().simple_list(data_state=1, begin_time__lte=self.begin_time)
        # 遍历巡检计划
        for plan_code, plan_items in plan_dict.items():
            plan_items['TestItems'] = list(InspectionPlanDB().retrieve(plan_code)['TestItems'].values())
            plan_items['inspection_plan_code'] = plan_code
            task_list = self.__generate_task(plan_code, plan_items)

            # 执行所有任务
            for task in task_list:
                InspectionTaskServer().create(**{**task, **{'create_time': int(time.time())}})
